const db = require('../config/db');

/**
 * 课程查询接口逻辑
 */
exports.listVideo = (req, res) => {
  //获取前端的参数
  let { category, page, size } = req.query;
  // 若 size = 3 请求的是第2页 则 当前页第一条数据在数据库中的索引 currPgDataIndex = (2-1)*3
  currPgDataIndex = (page - 1) * size;

  //查询课程列表sql
  const pageSql =
    'select * from video where del=0 and category=? order by id limit ?,?';

  //查询课程总数的sql
  const totalSql =
    'select count(*) as total from video where del=0 and category=?';

  db.query(
    pageSql,
    [category, Number(currPgDataIndex), Number(size)],
    (err, resPage) => {
      if (err) {
        return res.send({ code: 1, message: err.message });
      }
      db.query(totalSql, category, (err, resTotal) => {
        if (err) {
          return res.send({ code: 1, message: err.message });
        }
        res.send({
          code: 0,
          data: {
            list: resPage,
            total: resTotal[0].total,
          },
        });
      });
    }
  );
};

/**
 * 课程修改接口逻辑
 */
exports.updateVideoById = (req, res) => {
  let { title, price, id } = req.query;
  let sql = 'update video set ';
  let arr = [];
  //同时修改标题和价格
  if (title && price) {
    sql = sql + 'title=?,price=? where id=?';
    arr = [title, Number(price), Number(id)];
  } else if (title) {
    //单独修改标题
    sql = sql + 'title=? where id=?';
    arr = [title, Number(id)];
  } else if (price) {
    //单独修改标题
    sql = sql + 'price=? where id=?';
    arr = [price, Number(id)];
  }
  db.query(sql, arr, (err, results) => {
    if (err) {
      return res.send({ code: 1, message: err.message });
    }
    res.send({
      code: 0,
      data: { message: '修改成功' },
    });
  });
};

/**
 * 删除课程接口逻辑
 */
exports.deleteVideoById = (req, res) => {
  let { id } = req.query;

  let sql = 'update video set del=1 where id=?';
  db.query(sql, id, (err, results) => {
    if (err) {
      return res.send({ code: 1, message: err.message });
    }
    res.send({
      code: 0,
      data: {
        message: '删除成功',
      },
    });
  });
};

exports.createVideo = (req, res) => {
  let { title, course_img, price, point, category } = req.body;

  let totalSql =
    'select count(*) as total from video where del=0 and title=?';
  db.query(totalSql, title, (err, resTotal) => {
    if (resTotal[0].total > 0) {
      return res.send({
        code: 1,
        message: '该课程已存在',
      });
    } else {
      let sql =
        'insert into video (title,course_img,price,point,category) value(?,?,?,?,?)';
      db.query(
        sql,
        [title, course_img, price, point, category],
        (err, result) => {
          if (err) {
            return res.send({ code: 1, message: err.message });
          }
          res.send({
            code: 0,
            data: {
            },
            message: '添加成功',
          });
        }
      );
    }
  });
};
